<?php
/**
 * 用户管理类
 * 处理用户相关的增删改查操作
 */

class UserManager {
    private $db;
    
    public function __construct($database) {
        $this->db = $database;
    }
    
    /**
     * 获取所有用户列表
     */
    public function getAllUsers($page = 1, $limit = 10, $search = '') {
        $offset = ($page - 1) * $limit;
        
        $sql = "SELECT * FROM users WHERE 1=1";
        $params = [];
        
        if (!empty($search)) {
            $sql .= " AND (username LIKE ? OR full_name LIKE ? OR email LIKE ? OR department LIKE ?)";
            $searchTerm = "%{$search}%";
            $params = array_fill(0, 4, $searchTerm);
        }
        
        $sql .= " ORDER BY created_at DESC LIMIT ? OFFSET ?";
        $params[] = $limit;
        $params[] = $offset;
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 获取总数
        $countSql = "SELECT COUNT(*) as total FROM users WHERE 1=1";
        if (!empty($search)) {
            $countSql .= " AND (username LIKE ? OR full_name LIKE ? OR email LIKE ? OR department LIKE ?)";
        }
        
        $countStmt = $this->db->prepare($countSql);
        if (!empty($search)) {
            $countStmt->execute(array_fill(0, 4, $searchTerm));
        } else {
            $countStmt->execute();
        }
        $total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        return [
            'users' => $users,
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'total_pages' => ceil($total / $limit)
        ];
    }
    
    /**
     * 根据ID获取用户信息
     */
    public function getUserById($userId) {
        $sql = "SELECT * FROM users WHERE id = ?";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$userId]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    /**
     * 添加用户
     */
    public function addUser($userData) {
        $sql = "INSERT INTO users (username, password, role, email, full_name, department, position, phone, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $hashedPassword = password_hash($userData['password'], PASSWORD_DEFAULT);
        
        $stmt = $this->db->prepare($sql);
        return $stmt->execute([
            $userData['username'],
            $hashedPassword,
            $userData['role'],
            $userData['email'],
            $userData['full_name'],
            $userData['department'],
            $userData['position'],
            $userData['phone'],
            $userData['status']
        ]);
    }
    
    /**
     * 更新用户信息
     */
    public function updateUser($userId, $userData) {
        $sql = "UPDATE users SET username = ?, role = ?, email = ?, full_name = ?, 
                department = ?, position = ?, phone = ?, status = ?, updated_at = CURRENT_TIMESTAMP 
                WHERE id = ?";
        
        $stmt = $this->db->prepare($sql);
        return $stmt->execute([
            $userData['username'],
            $userData['role'],
            $userData['email'],
            $userData['full_name'],
            $userData['department'],
            $userData['position'],
            $userData['phone'],
            $userData['status'],
            $userId
        ]);
    }
    
    /**
     * 更新用户密码
     */
    public function updatePassword($userId, $newPassword) {
        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
        
        $sql = "UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?";
        $stmt = $this->db->prepare($sql);
        return $stmt->execute([$hashedPassword, $userId]);
    }
    
    /**
     * 删除用户
     */
    public function deleteUser($userId) {
        $sql = "DELETE FROM users WHERE id = ?";
        $stmt = $this->db->prepare($sql);
        return $stmt->execute([$userId]);
    }
    
    /**
     * 检查用户名是否已存在
     */
    public function usernameExists($username, $excludeUserId = null) {
        $sql = "SELECT COUNT(*) as count FROM users WHERE username = ?";
        $params = [$username];
        
        if ($excludeUserId) {
            $sql .= " AND id != ?";
            $params[] = $excludeUserId;
        }
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        return $result['count'] > 0;
    }
    
    /**
     * 获取用户统计信息
     */
    public function getUserStats() {
        $sql = "SELECT 
                COUNT(*) as total_users,
                SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as active_users,
                SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as inactive_users,
                SUM(CASE WHEN role = 'super_admin' THEN 1 ELSE 0 END) as super_admins,
                SUM(CASE WHEN role = 'user' THEN 1 ELSE 0 END) as normal_users,
                SUM(CASE WHEN role = 'guest' THEN 1 ELSE 0 END) as guests
                FROM users";
        
        $stmt = $this->db->query($sql);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
}
?>
